/**
 * org.assess.core.filter.UserSessionFilter
 */
package org.assess.core.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils;
import org.assess.core.bean.UserSession;
import org.assess.core.common.Constants;

/**
 * @description 用户Session的过滤器
 * @author XiaLongxiang
 * @createtime 2012-5-4 下午5:43:59
 */
public class UserSessionFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
            ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String currentURL = httpRequest.getRequestURI();
        String targetURL = currentURL.substring(currentURL.lastIndexOf("/"), currentURL.length());
        if (!("/login.jsp".equalsIgnoreCase(targetURL) || "/login.action".equalsIgnoreCase(targetURL) || "/Error.jsp"
                .equalsIgnoreCase(targetURL))) {
            HttpSession session = ((HttpServletRequest) request).getSession(false);
            UserSession usersession = session != null ? (UserSession) session.getAttribute(Constants.G_USER_SESSION)
                    : null;
            if (usersession == null || StringUtils.isBlank(usersession.getUserCode())) {
                // 用户登录以后需手动添加session
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");
                // 如果session为空表示用户没有登录就重定向到login.jsp页面
                return;
            }
        }
        chain.doFilter(request, response);
    }
    
    public void init(FilterConfig arg0) throws ServletException {
        
    }
    
    public void destroy() {
        
    }
}
